package com.zhxxfwzx.controller;

import com.zhxxfwzx.common.lang.RespBean;
import com.zhxxfwzx.entity.RegisterUser;
import com.zhxxfwzx.entity.SysUser;
import com.zhxxfwzx.entity.UserRole;
import com.zhxxfwzx.service.SysUserService;
import com.zhxxfwzx.service.UserRoleService;
import com.zhxxfwzx.service.impl.SysUserServiceImpl;
import org.springframework.context.annotation.Bean;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * (SysUser)控制层
 *
 * @author liJing
 * @since 2021-06-17 19:47:42
 */
@RestController
@RequestMapping("/user")
public class SysUserController {


    @Autowired
    SysUserService sysUserService;
    @Autowired
    UserRoleService userRoleService;

    @PostMapping("register")
    public RespBean RegisterUser(@RequestBody RegisterUser user){
        SysUser getUser = sysUserService.getUserByUsername(user.getUsername());
        if (getUser == null){
            SysUser inUser = new SysUser();
            //保存用户信息到用户表
            inUser.setUsername(user.getUsername());
            inUser.setPassword(new BCryptPasswordEncoder().encode(user.getPassword()));
            inUser.setUserFullname(user.getUserFullname());
            inUser.setTelephoneNumber(user.getTelephoneNumber());
            sysUserService.save(inUser);
            //保存角色信息到用户角色表
            UserRole userRole = new UserRole();
            userRole.setUserId(inUser.getUserId());
            userRole.setRoleKey(user.getRoleKey());
            userRoleService.save(userRole);
            //返回注册成功信息
            return RespBean.ok("用户注册成功,请登录...", user);
        }
        return RespBean.error("用户名已存在，请重新注册!");
    }

}
